/*
 * OpenNIConfiguration.cpp
 *
 *  Created on: Jun 23, 2011
 *      Author: sebastien
 */

#include "OpenNIConfiguration.h"
xn::UserGenerator g_UserGenerator;
XnStatus nRetVal = XN_STATUS_OK;
xn::Context context;
XnCallbackHandle h1, h2, h3;

int checkErrorCounter = 0;

void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& generator, XnUserID nId, void* pCookie) {
	printf("New User: %d\n", nId);
	g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(POSE_TO_USE,nId);
}

void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& generator, XnUserID nId, void* pCookie) {
	printf("User lost: %d\n", nId);
}

void XN_CALLBACK_TYPE Pose_Detected(xn::PoseDetectionCapability& pose, const XnChar* strPose,
		XnUserID nId, void* pCookie) {
	printf("Pose %s for user %d\n", strPose, nId);
	g_UserGenerator.GetPoseDetectionCap().StopPoseDetection(nId);
	g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}

void XN_CALLBACK_TYPE Calibration_Start(xn::SkeletonCapability& capability, XnUserID nId, void* pCookie) {
	printf("Starting calibration for user %d\n", nId);
}

void XN_CALLBACK_TYPE Calibration_End(xn::SkeletonCapability& capability, XnUserID nId,
		XnBool bSuccess, void* pCookie) {
	if (bSuccess) {
		printf("User calibrated\n");
		g_UserGenerator.GetSkeletonCap().StartTracking(nId);
	} else {
		printf("Failed to calibrate user %d\n", nId);
		g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(POSE_TO_USE, nId);
	}
}

void initOpenNIConfiguration(){
//	nRetVal = context.Init();
	xn::EnumerationErrors errors;
	nRetVal = context.InitFromXmlFile(CONFIG_XML_PATH, &errors);
	checkErrorCode (nRetVal, "context Init ");

	// Create the user generator
	nRetVal = g_UserGenerator.Create(context);
	checkErrorCode (nRetVal, "UserGenerator Create");

//	g_UserGenerator.GetMirrorCap().SetMirror(false);

	g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, h1);
	g_UserGenerator.GetPoseDetectionCap().RegisterToPoseCallbacks(Pose_Detected, NULL, NULL, h2);
	g_UserGenerator.GetSkeletonCap().RegisterCalibrationCallbacks(Calibration_Start, Calibration_End, NULL, h3);
	// Set the profile
	g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

	// Start generating
	nRetVal = context.StartGeneratingAll();
	checkErrorCode (nRetVal, "context StartGeneratingAll");
}

void shutdownOpenNIConfiguration() {
	context.Shutdown();
}
